package com.seestech.sell.web.agent;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.seestech.sell.common.annotation.RecordLog;
import com.seestech.sell.common.utils.Constants;
import com.seestech.sell.common.utils.JsonUtils;
import com.seestech.sell.common.utils.ResponseUtils;
import com.seestech.sell.domain.model.*;
import com.seestech.sell.service.IAgentGroupService;
import com.seestech.sell.service.IAgentService;
import com.seestech.sell.service.IUserAgentGroupService;
import com.seestech.sell.web.SuperController;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

import static java.awt.SystemColor.info;
import static org.apache.shiro.web.filter.mgt.DefaultFilter.user;


/**
 * Created by idiot on 2016/12/23.
 * @description 终端分组信息
 */
@Controller
@RequestMapping(value = "agent/agentGroup")
public class AgentGroupController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(AgentGroupController.class);

    @Resource
    private IAgentGroupService agentGroupService;
    @Resource
    private IAgentService agentService;
    @Resource
    private IUserAgentGroupService userAgentGroupService;

    //加载终端分组页面
    @RecordLog(value = "加载终端分组页面")
    @RequiresPermissions("agent:agentGroup:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String toPage(){
        logger.info("加载终端分组页面===>");
        return "agent/agentGroup/page";
    }

    //加载data页面
    @RequestMapping(value = "data", method = RequestMethod.POST)
    public String data(Model model, Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize, AgentGroup info){
        //从数据库获取终端分组列表信息
        User user = getUser();
        if(user != null){
            Page<AgentGroup> list = agentGroupService.getAllAgentGroupsByUserId(new RowBounds((pageNo-1)*pageSize, pageSize), user.getUserId(), info);
            model.addAttribute("lists",list);
        }
        return "agent/agentGroup/data";
    }

    //加载终端分组编辑页面
    @RequestMapping(value = "toUpdate", method = RequestMethod.GET)
    public String toAdd(Model model){
        return "agent/agentGroup/update";
    }

    //编辑终端分组信息
    @RecordLog(value = "修改终端分组信息")
    @ResponseBody
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(AgentGroup info){
        User user = getUser();
        if(user == null || user.getUserId() == null) {
            return ResponseUtils.responseError("用户信息有误，新增终端分组信息失败");
        }
        //根据名称获取终端分组
        List<AgentGroup> agentGroups = agentGroupService.getAgentGroupsByAgentGroupName(info.getAgentGroupName());
        //agentId为空/0时表示   新增操作
        if(info.getAgentGroupId() == null){
            if(agentGroups != null && agentGroups.size() > 0){
                return ResponseUtils.responseError("新增终端组失败，终端组名称已经存在");
            }
            info.setCreateUser(user.getUserId());   //创建人
            agentGroupService.insert(info);
            return ResponseUtils.responseSuccess("新增终端分组信息成功");
        }else {     //修改操作
            if(agentGroups != null && agentGroups.size() == 1){
                //获取第一个  判断主键是否相同  相同就允许修改
                AgentGroup agentGroup = agentGroups.get(0);
                if(!agentGroup.getAgentGroupId().equals(info.getAgentGroupId())){
                    return ResponseUtils.responseError("编辑终端组失败，终端组名称已经存在");
                }
            }else if (agentGroups != null && agentGroups.size() > 1){
                return ResponseUtils.responseError("编辑终端组失败，终端组名称已经存在");
            }
            info.setUpdateUser(user.getUserId());   //修改人
            agentGroupService.update(info);
            return ResponseUtils.responseSuccess("修改终端分组信息成功");
        }
    }

    //加载编辑页面
    @RequestMapping(value = "{agentGroupId}/toUpdate", method = RequestMethod.GET)
    public String toUpdate(@PathVariable("agentGroupId") long agentGroupId, Model model){
        AgentGroup agentGroup = agentGroupService.getAgentGroupByAgentGroupId(agentGroupId);
        model.addAttribute("agentGroup",agentGroup);
        return "agent/agentGroup/update";
    }

    //删除终端分组信息
    @RecordLog(value = "删除终端分组信息")
    @RequestMapping(value = "{agentGroupId}/delete", method = RequestMethod.POST)
    public void delete(@PathVariable("agentGroupId") long agentGroupId){
        //删除终端分组之前先判断该分组下是否有终端
        Long[] agentGroupIds = new Long[]{agentGroupId};
        List<Agent> list = agentService.getAgentsByAgentGroupIds(agentGroupIds);
        if(list != null && list.size() > 0){
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"该终端分组下有终端，请先移除终端");
        }else{
            User user = getUser();
            if(user != null){
                agentGroupService.delete(agentGroupId);
                //删除用户终端分组信息
                userAgentGroupService.deleteByIds(user.getUserId(), agentGroupIds);
                ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"删除终端分组信息成功");
            }else {
                ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"用户信息已经失效,请重新登录");
            }
        }
    }

    //批量删除
    @RequestMapping(value = "deleteBatch", method = RequestMethod.POST)
    public void deleteBatch(@RequestParam("ids[]") Long[] agentGroupIds){
        //删除终端分组之前先判断该分组下是否有终端
        List<Agent> list = agentService.getAgentsByAgentGroupIds(agentGroupIds);
        if(list != null && list.size() > 0){
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "所选终端分组下有终端，请先移除终端");
        }else {
            User user = getUser();
            if(user != null){
                agentGroupService.deleteBatch(agentGroupIds);
                //删除用户终端分组信息
                userAgentGroupService.deleteByIds(user.getUserId(), agentGroupIds);
                ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "批量删除终端分组信息成功");
            }else {
                ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(),"用户信息已经失效,请重新登录");
            }
        }
    }

    /************************************************/

    /**
     *  @description  获取终端分组信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getAgentGroups.json")
    public Object getAgentGroups(){
        ResultBean<Object> resultBean;
        User user = getUser();
        if(user != null){
            List<AgentGroup> agentGroups = agentGroupService.getAllValidAgentGroupsByUserId(user.getUserId());
            JSONArray object = JsonUtils.parseArray(agentGroups);
            resultBean = ResponseUtils.initResultBean(object, Constants.ResponseCode.success, "成功", true);
            resultBean.setTotalCount(agentGroups.size());
        }else {
            resultBean = ResponseUtils.initResultBean(null, Constants.ResponseCode.error, "失败", false);
        }
        return resultBean;
    }
}
